package com.xxxx.yoyo.dao.impl;

import java.util.List;
import java.util.Map;

import com.xxxx.yoyo.bean.User;
import com.xxxx.yoyo.dao.IUserDao;
import com.xxxx.yoyo.util.DBUtils;

public class UserDaoImpl implements IUserDao {

	/**
	 * 根据 用户名 获取用户
	 * @param username 用户名
	 * @return 返回查到的用户
	 */
	@Override
	public User selectUserByUsername(String username) {
		String sql = "SELECT * FROM user WHERE username = ?";
		User user = DBUtils.queryOne(sql, User.class, username);
		return user;
	}

	/**
	 * 添加用户
	 * @param user 要添加的用户
	 * @return 如果添加失败返回0, 添加成功返回1
	 */
	@Override
	public int insertUser(User user) {
		String sql = "INSERT into user(username, password, name, phone, address, status) VALUES(?, ?, ?, ?, ?, ?);";
		int row = DBUtils.update(sql, user.getUsername(), user.getPassword(), user.getName(), user.getPhone(), user.getAddress(), user.getStatus());
		return row;
	}

	/**
	 * 根据 用户名和密码 查询用户
	 * @param username 用户名
	 * @param password 密码
	 * @return 返回查到的用户
	 */
	@Override
	public User selectUserByUsernameAndPassword(String username, String password) {
		String sql = "SELECT * FROM user WHERE username = ? AND password = ? AND status = 1";
		User user = DBUtils.queryOne(sql, User.class, username, password);
		return user;
	}

	
	/**
	 * 更新用户信息
	 * @param user 用户信息
	 * @return 如果更新成功返回1, 否则返回0
	 */
	@Override
	public int updateUser(User user) {
		String sql = "UPDATE user SET  password = ? , name = ? , phone = ? , address = ? , status = ? WHERE id = ?";
		int row = DBUtils.update(sql, user.getPassword(), user.getName(), user.getPhone(), user.getAddress(), user.getStatus(), user.getId());
		return row;
	}

	/**
	 * 根据用户id查询用户信息
	 * @param userId 用户id
	 * @return 返回查到的用户
	 */
	@Override
	public User selectUserById(int userId) {
		String sql = "SELECT * FROM user WHERE id = ? AND status = 1";
		User user = DBUtils.queryOne(sql, User.class, userId);
		return user;
	}

	/**
	 * 获取用户列表
	 * @return 返回获取到的用户列表
	 */
	@Override
	public List<User> selectUserList() {
		String sql = "SELECT * FROM user WHERE status = 1";
		List<User> userList = DBUtils.query(sql, User.class);
		return userList;
	}

	/**
	 * 根据页码和每页条数获取用户列表
	 * @param page 页码
	 * @param size 每页条数
	 * @return 返回获取到的用户列表
	 */
	@Override
	public List<User> selectUserList(int page, int size) {
		String sql = "SELECT * FROM user WHERE status = 1 LIMIT ?, ?";
		List<User> userList = DBUtils.query(sql, User.class, (page-1)*size, size);
		return userList;
	}

	/**
	 * 获取用户数量
	 * @return 返回用户的数量
	 */
	@Override
	public long selectUserCount() {
		String sql = "SELECT count(*) AS count FROM user WHERE status = 1";
		Map<String,Object> map = DBUtils.queryOne(sql);
		long count = (Long)map.get ("count");
		return count;
	}

}
